#include "PreCompiledHeader.h"
#include "main.hpp"
#include "System.hpp"
#include "Window.hpp"
#include "Timer.h"
#include <time.h>


#pragma comment(lib, "ws2_32.lib")

// ---------------------------------------------------------------------------
// Globals
double	 g_appTime;

int WINAPI WinMain(HINSTANCE instanceH, HINSTANCE prevInstanceH, LPSTR command_line, int show)
{
	
	//Initialize SYSTEM
	if(SYSTEM->Initialize())
	{
		srand(time(NULL));
	}
	else
	{
		if(System::GetSystem() && SYSTEM->GetWindow())
		{
			MessageBox(SYSTEM->GetWindow()->GetHandle(), "Initialization error!\n", "Program Error", MB_OK | MB_ICONERROR);
		}
       

		gGameStateCurr = GS_QUIT;
	}

	//GameStateMgrInit(GS_ASTEROIDS);
	GameStateMgrInit(GS_MAINMENU);

	while(gGameStateCurr != GS_QUIT)
	{
		
		// If not restarting, load the gamestate
		if(gGameStateCurr != GS_RESTART)
		{
			GameStateMgrUpdate();
			GameStateLoad();
		}
		else
		{
			gGameStateNext = gGameStateCurr = gGameStatePrev;
		}
		// Initialize the gamestate
		GameStateInit();

		while(gGameStateCurr == gGameStateNext)
		{

			Timer::GetInstance()->UpdateNewTime();
			Timer::GetInstance()->UpdateDeltaTime();
			Timer::GetInstance()->UpdateCurrTime();			
			Timer::GetInstance()->FrameRateLocker();


			g_appTime += Timer::GetInstance()->GetDeltaTime();

			//FrameRateUpdateStart
			
			//InputUpdate
			
			//SYSTEM Update
			SYSTEM->Update();


			GameStateUpdate();

			GameStateDraw();
			
			//FrameRateUpdateEnd
			
			
		}
		
		GameStateFree();

		if(gGameStateNext != GS_RESTART)
		{
			GameStateUnload();
		}

		gGameStatePrev = gGameStateCurr;
		gGameStateCurr = gGameStateNext;
	}

	SYSTEM->Shutdown();

    return 0;
	
	//Check for memory Leak
	_CrtDumpMemoryLeaks();
}
